import { Component, Input, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";

import { EventService } from 'src/app/shared/service/event.service';
import { ModalController, Platform } from '@ionic/angular';
import { JPush } from '@jiguang-ionic/jpush/ngx';

import { CustomValidators } from "../../shared/custom-validators/custom-validators";
import { AppGlobalService } from "../../shared/service/app-global.service";
import { HttpService } from "../../shared/service/http.service";

@Component({
  selector: "app-change-pwd",
  templateUrl: "./change-pwd.component.html",
  styleUrls: [
    "../register/register.component.scss",
    "./change-pwd.component.scss",
    "../login/login.component.scss"
  ]
})
export class ChangePwdComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private http: HttpService,
    private modalCtrl: ModalController,
    private eventService: EventService,
    private appGlobalService: AppGlobalService,
    private jPush: JPush
  ) { }
  @Input() tagData: any = {};
  sessionId: string;
  open: boolean;

  form: FormGroup;
  mobileNum: any;
  mvcodeNum: any;
  usernameNum: any;
  passwordNum: any;
  passwordNum1: any;
  open1: any;

  positionInfo: any;

  // tslint:disable-next-line:no-inferrable-types
  time: number = -1;
  // tslint:disable-next-line:no-inferrable-types
  text: string = "获取验证码";
  mvcode: any;
  isLogin = false;
  appTypeCustom: any;
  changePwdModalTag = 'fw_changPwd_modal';//模态窗体标识

  async closeModal() {
    const modal = await this.modalCtrl.getTop();
    if (modal !== undefined) {
      modal.dismiss({ form: null });
    }
  }
  ngOnInit() {
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    this.isLogin = localStorage.getItem("loginStatus") ? true : false;
    this.sessionId = localStorage.getItem("sessionId");
    let mobile =
      localStorage.getItem("loginAccount") &&
        localStorage.getItem("loginAccount") !== "undefined"
        ? localStorage.getItem("loginAccount")
        : "";
    if (mobile && mobile.length > 11) {
      mobile = '';
    }
    const parttern = "[A-Za-z0-9]{6,30}";
    if (!this.tagData.data.mvcode) {
      this.form = this.fb.group({
        password: [
          "",
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(30),
            Validators.pattern(parttern)
          ]
        ],
        password1: [
          "",
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(30),
            Validators.pattern(parttern)
          ]
        ]
      });
    } else {

      this.form = this.fb.group({
        account: [
          { value: mobile },
          [
            Validators.required,
            Validators.minLength(11),
            Validators.maxLength(11),
            CustomValidators.phone
          ]
        ],
        mvcode: ["", [Validators.required, CustomValidators.vcode]],
        // username: ['', [Validators.required]],
        password: [
          "",
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(30),
            Validators.pattern(parttern)
          ]
        ],
        password1: [
          "",
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(30),
            Validators.pattern(parttern)
          ]
        ]
      });
    }

    this.mobileNum = mobile;
  }

  getErrors() {
    if (this.form.controls.account.errors) {
      if (this.form.controls.account.errors.required) {
        this.appGlobalService.showToast("请输入手机号码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的手机号码", 3000, "top");
      }
    } else if (this.form.controls.mvcode.errors) {
      if (this.form.controls.mvcode.errors.required) {
        this.appGlobalService.showToast("请输入验证码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的验证码", 3000, "top");
      }
    } else if (this.form.controls.password.errors) {
      if (this.form.controls.password.errors.required) {
        this.appGlobalService.showToast("请输入密码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的密码", 3000, "top");
      }
    } else if (this.form.controls.password1.errors) {
      if (this.form.controls.password1.errors.required) {
        this.appGlobalService.showToast("请再次输入密码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的密码", 3000, "top");
      }
    }
  }

  submit() {

    console.log(this.form, "erroerrrrr");
    if (this.form.status === "INVALID") {
      this.getErrors();
      return;
    } else if (this.passwordNum1 !== this.passwordNum) {
      this.appGlobalService.showToast("两次输入的密码不一致", 3000, "top");
      return;
    }
    const param = {
      content: Object.assign(this.form.value),
      id: this.tagData.data.sureButton.submit.id,
      sessionId: this.sessionId
    };
    delete param.content.password1;

    const password = this.appGlobalService.encryptDes(this.form.value.password);

    // 重新赋值
    param.content.password = password;
    param.content.account?'':param.content.account = this.mobileNum;

    this.http.post("application/submit", param, data => {
      // tslint:disable-next-line:no-string-literal
      if (data["success"]) {
        // 密码修改退出登录
        this.logout();
        localStorage.removeItem("loginAccount");
        this.appGlobalService.showToast("密码修改成功", 3000, "top");
        localStorage.setItem("useTarget", "true");
        localStorage.setItem("loginAccount", this.form.value.account);
        if (this.tagData.name && this.tagData.name === this.changePwdModalTag) {
          const modal = this.modalCtrl.getTop();
          if (modal) {
            this.modalCtrl.dismiss();
          }
        } else {
          const loginObj = {
            pageId: data.target,
            params: {},
            sessionId: this.sessionId
          };
          this.appGlobalService.goToForward(loginObj);
        }
      } else {
        // tslint:disable-next-line:no-string-literal
        this.appGlobalService.showToast(data["message"], 3000, "top");
      }
    });
  }

  logout() {
    if (localStorage.getItem('logoutParams')) {
      this.http.post("application/submit", JSON.parse(localStorage.getItem('logoutParams')), res => {
        localStorage.removeItem('logoutParams');
        if (res.success) {
          // // 退出时刷新顶部tab页面
          // localStorage.setItem("isRootURL", "true");
          // this.eventService.eventEmit.emit('refreshSubTabContainerForRootUrl', 'refreshSubTabContainerForRootUrl');
          if (res.data && res.data.badge) {
            res.data.badge.forEach(element => {
              const key = Object.keys(element)[0];
              if (Number(element[key]) >= 0) {
                this.eventService.eventEmit.emit("firstBadgeForTab", { [key]: Number(element[key]) });
              }
            });
          }
          // 2024.05.31 增加修改密码页  不需要验证码
          if (this.tagData.data.mvcode) {
            localStorage.setItem('needRefreshTab1', 'true');
            localStorage.setItem('needRefreshTab2', 'true');
            localStorage.setItem('needRefreshTab3', 'true');
            localStorage.setItem('needRefreshTab4', 'true');
            localStorage.setItem('needRefreshTab5', 'true');
            // this.appGlobalService.showToast(res.message, 1500, 'middle');
            localStorage.removeItem('userInfo');
            localStorage.removeItem('targetObj');
            localStorage.removeItem('loginStatus');
            this.appGlobalService.loginStatus = false;
            localStorage.removeItem('userInfo');
            localStorage.removeItem('tag.IconListLogic');
            localStorage.removeItem('tempPoint');
            localStorage.removeItem('userId');
            localStorage.removeItem('connUserId');
            localStorage.setItem('onLogoutWebSocketTag', 'true');
            localStorage.removeItem('isDetailPage');
            localStorage.removeItem('invitationArr');
            localStorage.removeItem('inMsgNum');
            localStorage.removeItem('isEnterDetailChatPage');
            this.jPush.deleteAlias({ sequence: 1 }).then((result) => {
              const sequence = result.sequence;
              console.log('删除别名成功' + sequence);
            }, (error) => {
              const sequence = error.sequence;
              const errorCode = error.code;
              console.log('删除别名失败：' + errorCode);
            });
            this.eventService.eventEmit.emit("onLogoutWebSocket", 'logout');
            //  刷新我的页面
            this.eventService.eventEmit.emit(localStorage.getItem('tab'), '1');
          }

        } else {
          // this.appGlobalService.showToast(res.message, 1500, 'middle');
        }
      });
    }

  }
  goToLogin() {
    const loginObj = {
      pageId: this.tagData.data.login.link.target,
      params: {},
      sessionId: this.sessionId
    };
    this.appGlobalService.goToForward(loginObj);
  }
  getVC(invalid) {
    console.log(this.form.get("account"));
    if (invalid) {
      this.appGlobalService.showToast("请输入正确手机号码", 3000, "top");
    } else {
      const params = {
        content: {
          mobile: this.form.value.account
        },
        id: this.tagData.data.codeButton.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post(
        "application/submit",
        params,
        (data: { success: any; data: { mvcode: any }; message: string }) => {
          if (data.success) {
            this.appGlobalService.showToast(
              "验证码已发送、请注意查收",
              3000,
              "top"
            );
            if (data.data) {
              this.mvcode = data.data.mvcode;
            }
            this.time = 90;
            const timer = setInterval(() => {
              this.time = this.time - 1;
              if (this.time === -1) {
                clearInterval(timer);
                this.text = "获取验证码";
              }
            }, 1000);
          } else {
            this.appGlobalService.showToast(data.message, 3000, "top");
          }
        }
      );
    }
  }
}
